import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import relativeTime from 'dayjs/plugin/relativeTime'
import duration from 'dayjs/plugin/duration'

// 配置dayjs
dayjs.locale('zh-cn')
dayjs.extend(relativeTime)
dayjs.extend(duration)

/**
 * 格式化日期时间
 */
export function formatDateTime(date: string | Date | number, format = 'YYYY-MM-DD HH:mm:ss'): string {
  if (!date) return '-'
  return dayjs(date).format(format)
}

/**
 * 格式化日期
 */
export function formatDate(date: string | Date | number, format = 'YYYY-MM-DD'): string {
  if (!date) return '-'
  return dayjs(date).format(format)
}

/**
 * 格式化时间
 */
export function formatTime(date: string | Date | number, format = 'HH:mm:ss'): string {
  if (!date) return '-'
  return dayjs(date).format(format)
}

/**
 * 相对时间
 */
export function formatRelativeTime(date: string | Date | number): string {
  if (!date) return '-'
  return dayjs(date).fromNow()
}

/**
 * 格式化持续时间
 */
export function formatDuration(seconds: number): string {
  if (!seconds || seconds < 0) return '0秒'
  
  const duration = dayjs.duration(seconds, 'seconds')
  
  if (seconds < 60) {
    return `${seconds}秒`
  } else if (seconds < 3600) {
    return `${duration.minutes()}分${duration.seconds()}秒`
  } else {
    return `${duration.hours()}时${duration.minutes()}分${duration.seconds()}秒`
  }
}

/**
 * 格式化文件大小
 */
export function formatFileSize(bytes: number): string {
  if (!bytes || bytes === 0) return '0 B'
  
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(1024))
  
  return `${(bytes / Math.pow(1024, i)).toFixed(2)} ${sizes[i]}`
}

/**
 * 格式化数字
 */
export function formatNumber(num: number, decimals = 0): string {
  if (num === null || num === undefined) return '-'
  
  return num.toLocaleString('zh-CN', {
    minimumFractionDigits: decimals,
    maximumFractionDigits: decimals
  })
}

/**
 * 格式化百分比
 */
export function formatPercent(num: number, decimals = 1): string {
  if (num === null || num === undefined) return '-'
  
  return `${num.toFixed(decimals)}%`
}

/**
 * 格式化货币
 */
export function formatCurrency(amount: number, currency = '¥'): string {
  if (amount === null || amount === undefined) return '-'
  
  return `${currency}${formatNumber(amount, 2)}`
}

/**
 * 格式化电流强度
 */
export function formatIntensity(intensity: number): string {
  if (intensity === null || intensity === undefined) return '-'
  
  return `${intensity.toFixed(1)}mA`
}

/**
 * 格式化频率
 */
export function formatFrequency(frequency: number): string {
  if (frequency === null || frequency === undefined) return '-'
  
  return `${frequency.toFixed(1)}Hz`
}

/**
 * 格式化治疗模式
 */
export function formatTreatmentMode(mode: string): string {
  const modeMap: Record<string, string> = {
    'tDCS+': 'tDCS+ (阳极)',
    'tDCS-': 'tDCS- (阴极)',
    'tACS': 'tACS (交流)'
  }
  
  return modeMap[mode] || mode
}

/**
 * 格式化治疗状态
 */
export function formatTreatmentStatus(status: string): string {
  const statusMap: Record<string, string> = {
    'completed': '已完成',
    'interrupted': '已中断',
    'cancelled': '已取消',
    'running': '进行中',
    'paused': '已暂停'
  }
  
  return statusMap[status] || status
}

/**
 * 格式化设备状态
 */
export function formatDeviceStatus(status: string): string {
  const statusMap: Record<string, string> = {
    'online': '在线',
    'offline': '离线',
    'maintenance': '维护中'
  }
  
  return statusMap[status] || status
}

/**
 * 格式化用户状态
 */
export function formatUserStatus(lastLogin: string): string {
  if (!lastLogin) return '未登录'
  
  const daysSinceLogin = dayjs().diff(dayjs(lastLogin), 'day')
  
  if (daysSinceLogin <= 7) return '活跃'
  if (daysSinceLogin <= 30) return '一般'
  return '沉睡'
}

/**
 * 格式化电池电量
 */
export function formatBatteryLevel(level: number): string {
  if (level === null || level === undefined) return '-'
  
  return `${level}%`
}

/**
 * 格式化IP地址
 */
export function formatIPAddress(ip: string): string {
  if (!ip) return '-'
  
  // 隐藏IP地址的最后一段
  const parts = ip.split('.')
  if (parts.length === 4) {
    return `${parts[0]}.${parts[1]}.${parts[2]}.***`
  }
  
  return ip
}

/**
 * 格式化手机号
 */
export function formatPhoneNumber(phone: string): string {
  if (!phone) return '-'
  
  // 隐藏手机号中间4位
  if (phone.length === 11) {
    return `${phone.slice(0, 3)}****${phone.slice(7)}`
  }
  
  return phone
}

/**
 * 截断文本
 */
export function truncateText(text: string, maxLength = 50): string {
  if (!text) return '-'
  
  if (text.length <= maxLength) return text
  
  return `${text.slice(0, maxLength)}...`
}

/**
 * 高亮搜索关键词
 */
export function highlightKeyword(text: string, keyword: string): string {
  if (!text || !keyword) return text
  
  const regex = new RegExp(`(${keyword})`, 'gi')
  return text.replace(regex, '<mark>$1</mark>')
}

/**
 * 格式化JSON
 */
export function formatJSON(obj: any, indent = 2): string {
  try {
    return JSON.stringify(obj, null, indent)
  } catch (error) {
    return String(obj)
  }
}